package com.chinatechstar.base.service.impl;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.chinatechstar.admin.entity.SysUser;
import com.chinatechstar.admin.mapper.SysUserMapper;
import com.chinatechstar.base.entity.SysProdOrg;
import com.chinatechstar.base.mapper.SysProdOrgMapper;
import com.chinatechstar.component.commons.constants.ProdConstants;
import com.chinatechstar.component.commons.exception.AjaxExceptionEnum;
import com.chinatechstar.component.commons.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinatechstar.base.entity.SysArea;
import com.chinatechstar.base.mapper.SysAreaMapper;
import com.chinatechstar.base.service.SysAreaService;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 业务逻辑实现层
 *
 * @author Rei
 */
@Service
@Transactional
public class SysAreaServiceImpl implements SysAreaService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final SequenceGenerator SEQUENCE_GENERATOR = new SequenceGenerator();

    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysProdOrgMapper sysProdOrgMapper;

    /**
     * 查询所有数据
     */
    @Override
    public List<SysArea> findSysAreaAll() {
        return sysAreaMapper.findSysAreaAll();
    }

    /**
     * 查询分页
     */
    @Override
    public List<LinkedHashMap<String, Object>> findSysAreaByCondition(Integer currentPage, Integer pageSize, String areaName, Long areaOrgId, String sorter) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("areaName", areaName);
        paramMap.put("areaOrgId", areaOrgId);
        if (StringUtils.isNotBlank(sorter)) {
            String sort = sorter.substring(0, sorter.lastIndexOf('_'));
            String sequence = "ascend".equals(sorter.substring(sorter.lastIndexOf('_') + 1)) ? "ASC" : "DESC";
            paramMap.put("sort", sort);
            paramMap.put("sequence", sequence);
        } else {
            paramMap.put("sort", "createTime");
            paramMap.put("sequence", "DESC");
        }
        List<LinkedHashMap<String, Object>> totalList = sysAreaMapper.findSysAreaByCondition(paramMap);

        return RecursiveListUtils.queryRecursiveList(totalList, ProdConstants.AREA_ID_FIELD, ProdConstants.AREA_PARENT_FIELD, ProdConstants.AREA_ROOT_ID);
    }

    /**
     * 查询导出数据列表
     */
    @Override
    public List<LinkedHashMap<String, Object>> findSysAreaForExcel(Map<String, Object> paramMap) {
        return sysAreaMapper.findSysAreaByCondition(paramMap);
    }

    /**
     * 根据主键ID数据查询数据
     */
    @Override
    public SysArea findSysAreaById(Long id) {
        return sysAreaMapper.findSysAreaById(id);
    }

    /**
     * 根据主键ID数组查询数据
     */
    @Override
    public List<SysArea> findSysAreaByIds(Long[] ids) {
        return sysAreaMapper.findSysAreaByIds(ids);
    }

    /**
     * 新增
     */
    @Override
    public void insertSysArea(SysArea sysArea) {
        getAndValidateSysArea(sysArea);

        SysUser currUser = sysUserMapper.getUserByUsername(CurrentUserUtils.getOAuth2AuthenticationInfo().get("name"));

        sysArea.setId(SEQUENCE_GENERATOR.nextId());
        sysArea.setCreateName(currUser.getNickname());
        sysArea.setCreateUsername(currUser.getUsername());
        sysAreaMapper.insertSysArea(sysArea);
        logger.info("已新增： {}", sysArea.getId());
    }

    /**
     * 批量新增
     */
    @Override
    public void insertSysAreas(List<SysArea> sysAreas) {
        SysUser currUser = sysUserMapper.getUserByUsername(CurrentUserUtils.getOAuth2AuthenticationInfo().get("name"));

        for (SysArea sysArea : sysAreas) {
            getAndValidateSysArea(sysArea);

            sysArea.setId(SEQUENCE_GENERATOR.nextId());
            sysArea.setCreateName(currUser.getNickname());
            sysArea.setCreateUsername(currUser.getUsername());
        }
        sysAreaMapper.insertSysAreas(sysAreas);
    }

    /**
     * 编辑
     */
    @Override
    public void updateSysArea(SysArea sysArea) {
        SysArea oldArea = sysAreaMapper.findSysAreaById(sysArea.getId());
        if (oldArea == null) {
            throw new IllegalArgumentException(AjaxExceptionEnum.AREA_NOT_FIND.getMsg());
        }

        // 验证A2 区块ID
        if (!sysArea.getAreaId().equals(oldArea.getAreaId())) {
            ValidateUtils.validateAreaId(sysArea.getAreaId());
        }

        // 验证A2 区块名称
        if (!sysArea.getAreaName().equals(oldArea.getAreaName())) {
            ValidateUtils.validateAreaName(sysArea.getAreaName());
        }

        // 验证父级
        if (!sysArea.getAreaParentId().equals(oldArea.getAreaParentId())) {
            ValidateUtils.validateParentArea(sysArea.getAreaParentId());
        }

        // 验证组织
        if (!sysArea.getAreaOrgId().equals(oldArea.getAreaOrgId())) {
            SysProdOrg prodOrg = ValidateUtils.validateProdOrg(sysArea.getAreaOrgId());
            sysArea.setAreaOrgName(prodOrg.getProdOrgName());
        }

        sysAreaMapper.updateSysArea(sysArea);
        logger.info("已编辑： {}", sysArea.getId());
    }

    /**
     * 批量编辑
     */
    @Override
    public void updateSysAreas(List<SysArea> sysAreas) {
        sysAreaMapper.updateSysAreas(sysAreas);
    }

    /**
     * 删除
     */
    @Override
    public void deleteSysAreaById(Long id) {
        sysAreaMapper.deleteSysAreaById(id);
    }

    /**
     * 批量删除
     */
    @Override
    public void deleteSysAreaByIds(Long[] ids) {
        sysAreaMapper.deleteSysAreaByIds(ids);
    }

    /**
     * 软删除
     */
    @Override
    public void softDeleteSysAreaById(Long id) {
        SysArea sysArea = sysAreaMapper.findSysAreaById(id);
        if (sysArea != null) {
            sysArea.setSoftDelete(0);
            sysAreaMapper.updateSysArea(sysArea);
        }

    }

    /**
     * 批量软删除
     */
    @Override
    public void softDeleteSysAreaByIds(Long[] ids) {
        List<SysArea> sysAreas = sysAreaMapper.findSysAreaByIds(ids);

        if (sysAreas.size() > 0) {
            for (SysArea sysArea : sysAreas) {
                sysArea.setSoftDelete(0);
            }

            sysAreaMapper.updateSysAreas(sysAreas);
        }
    }

    /**
     * 验证并且获取区块
     */
    private void getAndValidateSysArea(SysArea sysArea) {
        ValidateUtils.validateAreaName(sysArea.getAreaName());
        ValidateUtils.validateAreaId(sysArea.getAreaId());

        if (sysArea.getAreaParentId() != null) {
            ValidateUtils.validateParentArea(sysArea.getAreaParentId());
        }

        if (sysArea.getAreaOrgId() != null) {
            SysProdOrg prodOrg = ValidateUtils.validateProdOrg(sysArea.getAreaOrgId());
            sysArea.setAreaOrgName(prodOrg.getProdOrgName());
        }
    }
}
